from google.appengine.ext.webapp import RequestHandler, template
from google.appengine.ext import db
from model.token import OAuthRequestToken, OAuthAccessToken
import common.twitter_util as twitter_util
import handler.config as config
import logging
import pickle
import tweepy

class CallbackPage(RequestHandler):

    def get(self):
        oauth_token = self.request.get("oauth_token", None)
        oauth_verifier = self.request.get("oauth_verifier", None)
        if oauth_token is None:
            print template.render(
                'view/error.html', 
                {'message': 'Missing required parameters!'})
            return
        
        auth_handler = self.__fetch_auth_token(
            oauth_token, oauth_verifier, self.request.url)
        access_token = self.__store_auth_token(auth_handler)
        self.__make_friends(auth_handler)
        print template.render('view/account.html', 
                              {'access_token': access_token})
     
    def handle_exception(self, exception, debug_mode):
        if not exception:
            exception = 'unknown exceptoin' 
        print template.render('view/error.html', {'message': exception})
        
    def __fetch_auth_token(self, oauth_token, oauth_verifier, url):
        request_token = OAuthRequestToken.gql(
            "WHERE token_key=:key", key=oauth_token).get()
        if request_token is None:
            print template.render('view/error.html', 
                                  {'message': 'Invalid token!'})
            return
        auth_handler = tweepy.OAuthHandler(config.get_consumer_key(url), 
                                           config.get_consumer_secret(url), 
                                           None)
        auth_handler.set_request_token(request_token.token_key,
                                       request_token.token_secret)
        # Fetch the access token
        try:
            auth_handler.get_access_token(oauth_verifier)
            return auth_handler
        except tweepy.TweepError, e:
            logging.error(e)
            raise e
    
    def __store_auth_token(self, auth_handler):
        # Fetch user
        user = None
        try:
            user = auth_handler.get_username()
        except tweepy.TweepError, e:
            logging.error(e)
            raise e
        # Store access token
        access_token = OAuthAccessToken(
                key_name = user,
                token_key = auth_handler.access_token.key,
                token_secret = auth_handler.access_token.secret,
                id  = user
        )
        access_token.put()
        return access_token
    
    def __make_friends(self, user_auth_handler):
        self.__app_friends_user(user_auth_handler.get_username())
        self.__user_friends_app(user_auth_handler)      
    
    def __user_friends_app(self, user_auth_handler):
        if config.is_app_twitter_account(
            user_auth_handler.get_username(), self.request.url):
            return
        api = tweepy.API(
            auth_handler=user_auth_handler, secure=True, retry_count=3)
        api.create_friendship(
            id=config.get_app_twitter_account(self.request.url))

    def __app_friends_user(self, user):
        if config.is_app_twitter_account(user, self.request.url):
            return
        app_auth_handler = twitter_util.get_app_auth_handler(self.request.url)
        api = tweepy.API(auth_handler=app_auth_handler, secure=True, retry_count=3)
        api.create_friendship(id=user) 
